const express = require('express');
const app = express();
const http = require('http');
const server = http.createServer(app);

const { Server } = require("socket.io");
var io = new Server(server,{ cors: true });

const cors = require('cors')
app.use(cors())

const map=new Map()


io.on('connection', (socket) => {
    console.log('a user connected: '+socket.id);
    socket.on('disconnect', function (data) {
        console.log('user disconnected:',data)
        socket.broadcast.emit('off', {id:map.get(socket.id)});
    })

    // 将收到的信息广播给所有用户
    socket.on('message', function (data) {
        if (!map.has(socket.id))map.set(socket.id, data.id)
        socket.broadcast.emit('message', data);
    })
    
});

//设置跨域访问
app.all('*', function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header('Access-Control-Allow-Headers', 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild');
    res.header('Access-Control-Allow-Headers', ['mytoken','Content-Type']);
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By", ' 3.2.1');
    // res.header("Content-Type", "application/json;charset=utf-8");
    res.header("Content-Type", 'charset=utf-8');
    next();
});

server.listen(5959, () => {
    console.log('server on: http://localhost:5959');
});
